//
//  RecommendTableViewController.m
//  FlyGift
//
//  Created by lanou3g on 15/7/11.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "RecommendTableViewController.h"
#import "Recommend1TableViewCell.h"
#import "RecommendedModel.h"
#import "MJRefresh.h"


@interface RecommendTableViewController ()
@property(nonatomic,strong)NSMutableArray *modelArray;

@end

@implementation RecommendTableViewController

-(NSMutableArray * )modelArray
{
    if (!_modelArray) {
        self.modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

#pragma mark UITableView + 下拉刷新 动画图片
- (void)example02
{
    // 添加动画图片的下拉刷新
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    [self.tableView addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(Recommended)];

    // 设置普通状态的动画图片
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=2; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"icon_loading_action%ld@2x", i]];
        [idleImages addObject:image];
    }
    [self.tableView.gifHeader setImages:idleImages forState:MJRefreshHeaderStateIdle];
    
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=2; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"icon_loading_action%ld@2x", i]];
        [refreshingImages addObject:image];
    }
    [self.tableView.gifHeader setImages:refreshingImages forState:MJRefreshHeaderStatePulling];
    
    // 设置正在刷新状态的动画图片
    [self.tableView.gifHeader setImages:refreshingImages forState:MJRefreshHeaderStateRefreshing];
    // 在这个例子中，即将刷新 和 正在刷新 用的是一样的动画图片
    
    // 马上进入刷新状态
    [self.tableView.gifHeader beginRefreshing];
    
//    [self Recommended];
    // 此时self.tableView.header == self.tableView.gifHeader
}


// 利用第三方解析数据
-(void)Recommended
{
    //进行数据解析
    [LORequestManger GET:RecommendedURL success:^(id response) {
        //得到最外层的数组或者字典
        NSDictionary *dic = (NSDictionary *)response;
        //找到对应的字典
        NSDictionary *dic1 = dic[@"data"];
        NSArray *array = dic1[@"posts"];
//        self.modelArray = [NSMutableArray array];
        //遍历数组中的字典
        for (NSDictionary *dic2 in array)
        {
            RecommendedModel *model = [[RecommendedModel alloc]init];
            model.myImage = dic2[@"cover_image_url"];
            model.myNumber = (int)dic2[@"likes_count"];
            model.myTheTitle = dic2[@"title"];
            [self.modelArray addObject:model];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 这边打印的是当数据解析不成功的时候错误提示 这边也可以直接写nil
        NSLog(@"mainClasserror ----- %@",error);
    }];
    
    NSLog(@"-   -----%@",_modelArray);
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64)];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self example02];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _modelArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 180;
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *dentifier = @"cell";
    [tableView registerClass:[Recommend1TableViewCell class] forCellReuseIdentifier:dentifier];
    Recommend1TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:dentifier];
    
    //设置选中的cell 在你点击过后没有任何背景的效果
    cell.selectionStyle = UITableViewCellAccessoryNone;
    
    [cell.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    RecommendedModel *model = [_modelArray objectAtIndex:indexPath.row];
    
    cell.number.text = [NSString stringWithFormat:@"%d",model.myNumber];
    cell.label.text = model.myTheTitle;
    
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:model.myImage] placeholderImage:[UIImage imageNamed:@"285*176-1"] completed:nil];
    cell.button.tag = indexPath.row + 100;
    if (model.myBool == YES)
    {
        [cell.button setBackgroundImage:[UIImage imageNamed:@"like_normal@2x"] forState:UIControlStateNormal];
    }
    else
    {
        [cell.button setBackgroundImage:[UIImage imageNamed:@"like_press@2x"] forState:UIControlStateNormal];
    }
    return cell;
}



-(void)buttonAction:(UIButton *)button
{
    Recommend1TableViewCell *recommend1Cell = [[Recommend1TableViewCell alloc]init];
    recommend1Cell = (Recommend1TableViewCell *)button.superview.superview.superview;
    RecommendedModel *model = self.modelArray[button.tag - 100];
    
    if (model.myBool)
    {
        [recommend1Cell.button setBackgroundImage:[UIImage imageNamed:@"like_press@2x"] forState:UIControlStateNormal];
        recommend1Cell.number.text = [NSString stringWithFormat:@"%d",model.myNumber];
        
        
    }
    else
    {
        [recommend1Cell.button setBackgroundImage:[UIImage imageNamed:@"like_normal@2x"] forState:UIControlStateNormal];
        recommend1Cell.number.text = [NSString stringWithFormat:@"%d",model.myNumber + 1];
    }
    model.myBool = !model.myBool;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"123456");
}



/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
